package com.xfc.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xfc.common.core.domain.entity.SysDictData;
import com.xfc.common.core.redis.RedisCache;
import com.xfc.config.Result;
import com.xfc.config.Tools;
import com.xfc.school.domain.ScAuditionClassInfo;
import com.xfc.school.domain.ScCourse;
import com.xfc.school.domain.ScTeacher;
import com.xfc.school.service.IScAuditionClassInfoService;
import com.xfc.school.service.IScCourseService;
import com.xfc.school.service.IScTeacherService;
import com.xfc.system.service.ISysDictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 *  试听课接口
 * @author lcj
 */
@Slf4j
@RestController
@Api(tags = "试听课接口")
@Validated
@RequestMapping("/api/audition")
public class WxAuditionController {

    @Autowired
    private IScAuditionClassInfoService auditionClassInfoService;

    @Autowired
    private IScCourseService courseService;

    @Autowired
    private IScTeacherService scTeacherService;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private ISysDictTypeService sysDictTypeService;
    @Autowired
    private RedisCache redisUtils;


    /**短信模板*/
    @Value("${wx.templateId.a}")
    private String tema;

    /**
     *  轮播图片
     * @return 轮播图片
     */
    @GetMapping("/getimagesList")
    @ApiOperation(value = "轮播图片")
    public Result<?> getimagesList(){
        JSONObject jsonObject=new JSONObject();
        List<String> list= new ArrayList<>();
        list.add("https://joolun-base-test.oss-cn-zhangjiakou.aliyuncs.com/1/material/bd7e2a80-d1ad-4b52-b896-dd24e0883484.jpg");
        list.add("https://joolun-base-test.oss-cn-zhangjiakou.aliyuncs.com/1/material/984f23d4-680c-4f2c-bdee-58ad44fb244a.jpg");
        list.add("https://joolun-base-test.oss-cn-zhangjiakou.aliyuncs.com/1/material/bcb47e84-d8a2-4660-bdf1-d81b889db8e3.jpg");
        jsonObject.put("url",list);
        jsonObject.put("name","轮播图片");
        jsonObject.put("desc","详情");
        return Result.ok(jsonObject);
    }


    /**
     *  根据类型查询课程列表
     * @return 查询课程列表
     */
    @GetMapping("/getAuditionList")
    @ApiImplicitParams({
            @ApiImplicitParam( name = "typeId", value =  "类型id",  dataType = "String",required = true),
            @ApiImplicitParam( name = "Page", value =  "Page",  dataType = "Page"),
    })
    @ApiOperation(value = "根据类型查询课程列表")
    public Result<?> getAuditionList(Page<ScCourse> page,@NotBlank @RequestParam String typeId){

        return Result.ok(courseService.page(page,new QueryWrapper<ScCourse>().eq("type",typeId).eq("state",0)));
    }

    /**
     * 查询所有课程列表
     * @return Result
     */
    @GetMapping("/getAllCourse")
    @ApiImplicitParams({
            @ApiImplicitParam( name = "className", value =  "课程名称",  dataType = "String"),
            @ApiImplicitParam( name = "type", value =  "课程类型",  dataType = "String")
    })
    @ApiOperation(value = "查询所有课程列表")
    public Result<?> getAllCourse(@NotBlank @RequestParam String type,String className){
        QueryWrapper<ScCourse> queryWrapper=new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(className),"class_name",className);
        queryWrapper.eq("state",0);
        queryWrapper.eq("type",type);
        queryWrapper.select("id","class_name");
        return Result.ok(courseService.list(queryWrapper));
    }

    /**
     *  根据课程id查询课程详情
     * @return 根据课程id查询课程信息
     */
    @GetMapping("/getCourseById")
    @ApiOperation(value = "根据课程id查询课程详情")
    @ApiImplicitParams({
            @ApiImplicitParam( name = "id", value =  "课程id",  dataType = "String",required = true),
            @ApiImplicitParam( name = "opendId", value =  "openId",  dataType = "String"),
    })
    public Result<?> getCourseById(@NotBlank @RequestParam String id,String openId){
        //查询用户信息
        ScCourse course=courseService.getById(id);
        if (Objects.isNull(course)){
            return Result.error("没有查询到课程信息");
        }
//        if (StringUtils.isNotEmpty(openId)){
//            ScAuditionClassInfo auditionClassInfo=auditionClassInfoService.getOne(new QueryWrapper<ScAuditionClassInfo>().eq("applicant_openId",openId).eq("course_no",id));
//            if (Objects.nonNull(auditionClassInfo)){
//                course.setCourseStatus(auditionClassInfo.getStatus());
//            }else {
//                log.info("查询状态："+course.getCourseStatus());
//            }
//        }
        return Result.ok(course);
    }


    /**
     *
     * @return string
     */
    @ApiOperation("获取课程类型")
    @GetMapping("/getCourseType")
    public Result<?> getCourseType(){
        //查询通知人信息
        List<SysDictData> sysDictDataList=sysDictTypeService.selectDictDataByType("sc_class_type");
        List<Object> resList=new ArrayList<>();
        sysDictDataList.forEach(l->{
            JSONObject json=new JSONObject();
            json.put("text",l.getDictLabel());
            List<Object> childrenList=new ArrayList<>();
            //查询所有课程
            List<ScCourse> scCourses=courseService.list(Wrappers.<ScCourse>lambdaQuery().eq(ScCourse::getType,l.getDictValue()).eq(ScCourse::getState,0));
            scCourses.forEach(m->{
                JSONObject childrenJson=new JSONObject();
                childrenJson.put("id",m.getId());
                childrenJson.put("text",m.getClassName());
                childrenList.add(childrenJson);
            });
            json.put("children",childrenList);
            resList.add(json);
        });
        return Result.ok(resList);
    }


    /**
     *  预约试听课程
     * @return 预约试听课程
     */
    @PostMapping("/addAuditionCourse")
    @ApiOperation(value = "预约试听课程")
    @ApiImplicitParams({
            @ApiImplicitParam( name = "applicant", value =  "申请人名称",  dataType = "String",required = true),
            @ApiImplicitParam( name = "applicantMobile", value =  "申请人手机号",  dataType = "String",required = true),
            @ApiImplicitParam( name = "courseId", value =  "课程id",  dataType = "String",required = true),
            @ApiImplicitParam( name = "applicantAge", value =  "申请人年龄",  dataType = "int",required = true),
            @ApiImplicitParam( name = "openId", value =  "openId",  dataType = "String",required = true),
            @ApiImplicitParam( name = "remarks", value =  "备注",  dataType = "String")
    })
    public Result<?> addAuditionCourse(@NotBlank @RequestParam String applicant,
                                       @NotNull @RequestParam String applicantMobile,
                                       @NotNull @RequestParam Integer applicantAge,
                                       @NotBlank @RequestParam String openId,
                                       @NotBlank @RequestParam String courseId,String remarks,
                                       @NotNull @RequestParam Integer code, String sale){
        //验证验证码
        Integer redisCode=redisUtils.getCacheObject(Tools.SMS_CODE+applicantMobile);
        log.info("输出验证码：{}",code);
        log.info("输出redis验证码：{}",redisCode);
        if (!Objects.equals(code, redisCode)){
            return Result.error("验证码不正确");
        }
        //查询课程信息
        ScCourse course=courseService.getById(courseId);
        if (Objects.isNull(course)){
            return Result.error("没有查询到课程信息");
        }
        //查询通知人信息
        List<SysDictData> sysDictDataList=sysDictTypeService.selectDictDataByType("sys_yy_open_id");

        ScAuditionClassInfo auditionClassInfo=new ScAuditionClassInfo();
        auditionClassInfo.setCreateTime(new Date());
        auditionClassInfo.setStatus(0);
        auditionClassInfo.setCourseName(course.getClassName());
        auditionClassInfo.setCourseNo(course.getId());
        auditionClassInfo.setApplicant(applicant);
        auditionClassInfo.setApplicantAge(applicantAge);
        auditionClassInfo.setApplicantOpenid(openId);
        auditionClassInfo.setApplicantMobile(applicantMobile);
        auditionClassInfo.setRemarks(remarks);
        //销售员信息
        auditionClassInfo.setSale(sale);
        //添加预约信息
        auditionClassInfoService.save(auditionClassInfo);
        //试听课预约
        sendMessage(applicant,applicantMobile,course.getClassName(),sysDictDataList.get(0).getDictLabel());
        return Result.ok("预约信息添加成功");
    }

    /**
     * 查询所有在职老师
     * @return Result
     */
    @PostMapping("/getAllTeacher")
    @ApiOperation(value = "查询所有在职老师")
    public Result<?> getAllTeacher(){
        return Result.ok(scTeacherService.list(new QueryWrapper<ScTeacher>().eq("state",0)));
    }

    /**
     *  试听课预约
     * @param name 姓名
     * @param mobile 手机号
     * @param courseName 课程名称
     * @param openId openid
     */
    private void sendMessage(String name,String mobile,String courseName,String openId){

        // 发送模板消息接口
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                // 模板id
                .templateId(tema)
                // 模板跳转链接.url("http://81.69.173.26")
                .build();
        // 添加模板数据
        templateMessage.addData(new WxMpTemplateData("first", "您有新的课程报名消息，请及时查看确认。\n", "#173177"))
                .addData(new WxMpTemplateData("keyword1", name, "#173177"))
                .addData(new WxMpTemplateData("keyword2", mobile, "#173177"))
                .addData(new WxMpTemplateData("keyword3", DateUtil.now(), "#173177"))
                .addData(new WxMpTemplateData("keyword4", courseName, "#173177"))
                .addData(new WxMpTemplateData("remark", "如有疑问，可拨打热线51219359询问，谢谢！", "#173177"))
                .setToUser(openId);
        // 发送模板消息
        String msgId = "";
        try {
             msgId  = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            log.error("试听课预约信息发送成功,{},openId:,{}",msgId,openId);
        } catch (WxErrorException e) {
            log.error("模板信息发送失败,失败原因{}",msgId);
            e.printStackTrace();
        }
    }




}
